//
//  EFAPjtMgrWithRoleVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/10/26.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAPjtMgrWithRoleVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "EFAProjectTCell.h"
#import "EFAModel.h"
#import "EFADeviceVC.h"
#import "EFAPjtMapVC.h"
#import "UIColor+XDHex.h"
#import "GlobalHeader.h"
#import "EFAMsgVC.h"
#import "EFAPjtAddVC.h"
#import "EFAPjtDetailVC.h"
#import "EFAReportVC.h"
#import "EFAPjtMgrResultsTVC.h"
#import "UIImage+XDAdd.h"
#import "EFAPjtManagerVC.h"

@interface EFAPjtMgrWithRoleVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, UISearchResultsUpdating, UISearchBarDelegate, UISearchControllerDelegate>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
//@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) UIBarButtonItem *mapBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *addBarBtnItem;
@property (strong, nonatomic) UISearchController *searchController;
@property (strong, nonatomic) UISegmentedControl *segCtrl;
@property (nonatomic, assign) EFAPjtMgrRoleType viewType;

@property (nonatomic, strong) EFAProjectModel *ownPjtModel;
@property (nonatomic, strong) EFAProjectModel *otherPjtModel;
@property (nonatomic, readonly) EFAProjectModel *projectModel;
//@property (nonatomic, strong) EFAPjtListItem *searchItem;
@end

static NSString *const kReuseCellId = @"EFAProjectTCell";
//static NSInteger const kRequestUserSize = 20;

@implementation EFAPjtMgrWithRoleVC

#pragma mark - life cycle
//- (instancetype)initWithViewType:(EFAPjtMgrRoleType)viewType {
//    self = [super init];
//    if (self) {
//        _viewType = viewType;
////        if (viewType != EFAPjtManagerVCTypeManager) {
////            _projectModel = [EFAModel sharedInstance].projectModel;
////        }
//    }
//    return self;
//}
//- (instancetype)init {
//    NSAssert(NO, @"use initWithViewType");
//    return nil;
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initLogicData];
    [self initNavigationBar];
    [self initSubViews];
}
- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}
- (void)initLogicData {
    if (([EFAModel sharedInstance].loginInfo.user_info.efairyrole_level == EFALoginUserRoleAdmin)) {
        self.viewType = EFAPjtMgrRoleTypeOther;
    } else {
        self.viewType = EFAPjtMgrRoleTypeOwn;
    }
}
- (void)initNavigationBar {
//    NSArray *titleArray = @[@"选择项目", @"选择项目", @"项目管理", @"选择项目"];
//    self.navigationItem.title = @"角色项目";
    self.navigationItem.titleView = self.segCtrl;
    
    self.navigationItem.rightBarButtonItem = self.addBarBtnItem;
    BOOL isAgency = ([EFAModel sharedInstance].loginInfo.user_info.efairyrole_level < EFALoginUserRoleAdmin);
    if (!isAgency) {
        self.navigationItem.rightBarButtonItem = nil;
    }
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}
- (void)initSubViews {
    self.definesPresentationContext = YES;  ///< 这里会影响到搜索结果页面的下拉刷新那里的偏移量
    if (@available(iOS 11.0, *)) {
        self.navigationItem.searchController = self.searchController;
    } else {
        UIView *headerBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 44)];
        //    headerBgView.backgroundColor = [UIColor whiteColor];
        [headerBgView addSubview:self.searchController.searchBar];
        self.tableView.tableHeaderView = headerBgView;
        //    self.tableView.tableHeaderView = self.searchController.searchBar; ///< 直接设置为headerview，体验最好，但是mjrefresh会受到影响，蛋疼
    }
    
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    //    self.tableView.mj_footer = self.mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有项目" attributes:dic];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"global_empty"];
}
//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 1;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.projectModel.project_list.count;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.viewType == EFAPjtMgrRoleTypeOwn) {
        return YES;
    }
    
    return NO;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self deletePjtWithIndexPath:indexPath];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EFAProjectTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.row < self.projectModel.project_list.count) {
        [cell configViewWithPjtItem:self.projectModel.project_list[indexPath.row]];
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row < self.projectModel.project_list.count) {
        EFAPjtListItem *item = self.projectModel.project_list[indexPath.row];
        [self jumpToSomeVCWithProjectItem:item];
    }
}
#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchString = searchController.searchBar.text;
    if (!searchString.length) {
        return;
    }
    NSLog(@"输入的搜索词语是%@", searchString);
    
    // hand over the filtered results to our search results table
    EFAPjtMgrResultsTVC *tableController = (EFAPjtMgrResultsTVC *)self.searchController.searchResultsController;
    tableController.keywords = searchString;
    tableController.viewType = EFAPjtManagerVCTypeManager;
    tableController.roleType = self.viewType;
    [tableController refreshNewData];
}

#pragma mark - UISearchControllerDelegate
- (void)didPresentSearchController:(UISearchController *)searchController {
    //    CGFloat statusHeight = CGRectGetHeight([[UIApplication sharedApplication] statusBarFrame]);
    //    CGFloat tabHeight = CGRectGetHeight(self.tabBarController.tabBar.frame);
    //
    //    if (self.viewType == EFAPjtManagerVCTypeManager || self.viewType == EFAPjtManagerVCTypeReport) {
    //        self.tableView.contentInset = UIEdgeInsetsMake(statusHeight, 0, 0, 0);
    //    } else {
    //        self.tableView.contentInset = UIEdgeInsetsMake(statusHeight, 0, tabHeight, 0);
    //    }
}
- (void)didDismissSearchController:(UISearchController *)searchController {
    //    CGFloat statusHeight = CGRectGetHeight([[UIApplication sharedApplication] statusBarFrame]);
    //    CGFloat navHeight = CGRectGetHeight(self.navigationController.navigationBar.frame);
    //    CGFloat tabHeight = CGRectGetHeight(self.tabBarController.tabBar.frame);
    //
    //    if (self.viewType == EFAPjtManagerVCTypeManager || self.viewType == EFAPjtManagerVCTypeReport) {
    //        self.tableView.contentInset = UIEdgeInsetsMake(statusHeight + navHeight, 0, 0, 0);
    //    } else {
    //        self.tableView.contentInset = UIEdgeInsetsMake(statusHeight + navHeight, 0, tabHeight, 0);
    //    }
    //
    //    [self.tableView setContentOffset:CGPointMake(0, -statusHeight-navHeight) animated:YES];
    
    //    self.searchController.searchBar.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 44);
}

#pragma mark - event response
- (void)segCtrlValueChange:(UISegmentedControl *)segment {
    self.viewType = segment.selectedSegmentIndex;
    if (!self.projectModel) {
        [self requestPjtListWithHeader:YES];
    } else {
        [self refreshWholeView];
    }
}
- (void)mapBarBtnTapped:(UIBarButtonItem *)item {
    EFAPjtMapVC *vc = [[EFAPjtMapVC alloc] init];
    vc.pjtModel = self.projectModel;
    [self showViewController:vc sender:nil];
}
- (void)addBarBtnTapped:(UIBarButtonItem *)item {
    EFAPjtAddVC *vc = [[EFAPjtAddVC alloc] initWithViewType:EFAPjtAddVCTypeAdd];
    vc.successHandle = ^{
        [self.tableView.mj_header beginRefreshing];
    };
    [self showViewController:vc sender:nil];
}
//#pragma mark - EFAPjtMgrResultsTVCDelegate
//- (void)pjtMgrResultsTVC:(EFAPjtMgrResultsTVC *)vc didSelectPjtListItem:(EFAPjtListItem *)item {
//    // 搜索界面消失
//    [self.searchController setActive:NO];
//    // 根据搜索结果，跳转
//    self.searchItem = item;
//}

#pragma mark - private methods
- (void)deletePjtWithIndexPath:(NSIndexPath *)indexPath {
    UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"确定要删除该项目吗?" message:@"删除该项目之后，所有项目相关信息都不可恢复" preferredStyle:UIAlertControllerStyleAlert];
    [vc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [vc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self requestDeletePjtWith:indexPath];
    }]];
    [self showDetailViewController:vc sender:nil];
}
- (void)jumpToSomeVCWithProjectItem:(EFAPjtListItem *)item {
//    if (self.viewType == EFAPjtManagerVCTypeMsg) {
//        [self jumpToMsgVCWithProjectItem:item];
//    } else if(self.viewType == EFAPjtManagerVCTypeDevice) {
//        [self jumpToDeviceWithProjectItem:item];
//    } else if(self.viewType == EFAPjtManagerVCTypeManager) {
        [self jumpToPjtDetailWithPjtItem:item];
//    } else if (self.viewType == EFAPjtManagerVCTypeReport) {
//        [self jumpToReportWithPjtItem:item];
//    }
}
- (void)jumpToMsgVCWithProjectItem:(EFAPjtListItem *)item {
    EFAMsgVC *vc = [[EFAMsgVC alloc] init];
    vc.project_id = item.efairyproject_id;
    [self showViewController:vc sender:nil];
}
- (void)jumpToDeviceWithProjectItem:(EFAPjtListItem *)item {
    EFADeviceVC *vc = [[EFADeviceVC alloc] init];
    vc.project_id = item.efairyproject_id;
    vc.project_name = item.efairyproject_name;
    [self showViewController:vc sender:nil];
}
- (void)jumpToPjtDetailWithPjtItem:(EFAPjtListItem *)item {
    EFAPjtDetailVC *vc = [[EFAPjtDetailVC alloc] init];
    vc.project_id = item.efairyproject_id;
    [self showViewController:vc sender:nil];
}
- (void)jumpToReportWithPjtItem:(EFAPjtListItem *)item {
    EFAReportVC *vc = [[EFAReportVC alloc] init];
    vc.project_id = item.efairyproject_id;
    vc.project_name = item.efairyproject_name;
    [self showViewController:vc sender:nil];
}
- (void)refreshWholeView {
    //    // 尾部加载更多的显示
    //    if (self.userList.totalLoad) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestPjtListWithHeader:isHeader];
}

#pragma mark - network request
- (void)requestPjtListWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"manage_type" : @(self.viewType)};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiPjtManagerList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求项目列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        EFAProjectModel *temp = [EFAProjectModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        if (self.viewType == EFAPjtMgrRoleTypeOwn) {
            self.ownPjtModel = temp;
        } else {
            self.otherPjtModel = temp;
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求项目列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}
- (void)requestDeletePjtWith:(NSIndexPath *)indexPath {
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    if (indexPath.row >= self.projectModel.project_list.count) {
        return;
    }
    EFAPjtListItem *item = self.projectModel.project_list[indexPath.row];
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairyproject_id_list" : [@[@(item.efairyproject_id)] yy_modelToJSONString]};
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    [[XDAFNetworking sharedInstance] DELETE:[ApiManager apiProject] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求删除项目返回：%@", responseObject);
        [hud hideAnimated:YES];
        [self.projectModel.project_list removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求删除项目失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}
#pragma mark - getters and setters
- (UISegmentedControl *)segCtrl {
    if (!_segCtrl) {
        _segCtrl = [[UISegmentedControl alloc] initWithItems:@[@"自创建项目", @"代管理项目"]];
        [_segCtrl addTarget:self action:@selector(segCtrlValueChange:) forControlEvents:UIControlEventValueChanged];
        [_segCtrl setTintColor:[UIColor xd_colorWithHex:EFAGlobalColorDarkGreen]];
        _segCtrl.selectedSegmentIndex = self.viewType;
    }
    return _segCtrl;
}
- (UIBarButtonItem *)mapBarBtnItem {
    if (!_mapBarBtnItem) {
        _mapBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"device_map"] style:UIBarButtonItemStylePlain target:self action:@selector(mapBarBtnTapped:)];
    }
    return _mapBarBtnItem;
}
- (UIBarButtonItem *)addBarBtnItem {
    if (!_addBarBtnItem) {
        _addBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"新增" style:UIBarButtonItemStylePlain target:self action:@selector(addBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_addBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
    }
    return _addBarBtnItem;
}
- (UISearchController *)searchController {
    if (!_searchController) {
        EFAPjtMgrResultsTVC *tvc = [[EFAPjtMgrResultsTVC alloc] init];
        //        tvc.delegate = self;
        _searchController = [[UISearchController alloc] initWithSearchResultsController:tvc];
        _searchController.searchResultsUpdater = self; ///< 设置UISearchControllerDelegate协议代理
        _searchController.dimsBackgroundDuringPresentation = YES;///<是否添加半透明覆盖层
        _searchController.hidesNavigationBarDuringPresentation = YES;///< 是否隐藏导航栏
        _searchController.delegate = self;
        _searchController.searchBar.delegate = self;
        _searchController.searchBar.placeholder = @"输入项目名称";
        //设置背景图是为了去掉上下黑线
        if (@available(iOS 11.0, *)) {
            ;
        } else {
            UIImage* searchBarBg = [UIImage xd_getImageWithColor:[UIColor whiteColor] andHeight:1.0f];
            [_searchController.searchBar setBackgroundImage:searchBarBg forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            _searchController.searchBar.barTintColor = [UIColor whiteColor];
            UITextField *searchField = [_searchController.searchBar valueForKey:@"searchField"];
            if (searchField) {
                [searchField setBackgroundColor:[UIColor xd_colorWithHex:0xEEEEEE]];
                searchField.layer.cornerRadius = 4.0f;
                searchField.layer.masksToBounds = YES;
            }
        }
        
        [_searchController.searchBar sizeToFit];
        _searchController.searchBar.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 44);
    }
    return _searchController;
}
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}
- (EFAProjectModel *)projectModel {
    return (self.viewType == EFAPjtMgrRoleTypeOwn) ? self.ownPjtModel : self.otherPjtModel;
}
@end
